package edu.suda.xsap.security;

import com.codevip.tutorial.controller.common.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;


/*************************************
 * Date: 20.10.26
 * For:页面异常之访问拒绝异常处理
 */
@Component
@Slf4j
public class JwtWebAccessDeniedHandler implements AccessDeniedHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        log.debug("---> 进入AccessDeniedHandler中的handle方法:" + e);
        Result result = Result.failure("用户无操作或访问权限，需要继续访问 请切换账户 或 联系管理员获取权限",request.getRequestURI());
        result.setCode(HttpServletResponse.SC_FORBIDDEN);
        //
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //
        String json = objectMapper.writeValueAsString(result);
        PrintWriter printWriter = response.getWriter();
        printWriter.print(json);
        printWriter.flush();
        printWriter.close();
    }
}
